package com.itheima.controller;

import com.itheima.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class UploadController {
    @Value("${reggide.url}")
    private String uploadPath;

    @PostMapping("/upload")
    public R getFile(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        int i = originalFilename.lastIndexOf(".");
        String substring = originalFilename.substring(i);
        String uuidName = UUID.randomUUID().toString() + substring;
        try {
            file.transferTo(new File(uploadPath + uuidName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(uuidName);
    }

    @GetMapping("/download")
    public void getImg(String name, HttpServletResponse response) {
        try {
            FileInputStream fis = new FileInputStream(uploadPath + name);
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] bytes = new byte[1024];
            int len = -1;
            while ((len = fis.read(bytes)) != -1) {
                outputStream.write(bytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
